import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import '../../const/common_const.dart';
import '../../request/api.dart';
import '../../request/requestManager.dart';
class ForgetPassWordController extends GetxController {


  TextEditingController phoneController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  TextEditingController codeController = TextEditingController();
  bool isCountingDown = false;
  int countdownSeconds = 60;
  Timer? timer;

  /// 获取验证码
  getSmsCode() async {
    if (!phoneController.text.isPhoneNumber) {
      EasyLoading.showToast(LoginStringConst.inputCorrectPhone);
      return;
    }
    if (passwordController.text.length < 6 || passwordController.text.length > 20) {
      EasyLoading.showToast(LoginStringConst.passwordTips);
      return;
    }
    if (isCountingDown) return;
    startCountdown();

    var result = await RequestManager().post(API.getSmsCode,params: {'mobile':phoneController.text,'type':'forget'});
    if (result != null && result['code'] == 200) {
      EasyLoading.showToast('验证码已发送');
    }
  }

  /// 开始倒计时
  void startCountdown() {
    isCountingDown = true;
    countdownSeconds = 10;
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      countdownSeconds--;
      update();
      if (countdownSeconds <= 0) {
        isCountingDown = false;
        timer.cancel();
      }
    });
  }

  /// 修改
  void submitClick() async {
    if (!phoneController.text.isPhoneNumber) {
      EasyLoading.showToast(LoginStringConst.inputCorrectPhone);
      return;
    }
    if (passwordController.text.length < 6 || passwordController.text.length > 20) {
      EasyLoading.showToast(LoginStringConst.passwordTips);
      return;
    }
    if (codeController.text == '') {
      EasyLoading.showToast(LoginStringConst.inputVerCodeText);
      return;
    }
    var params = {
      'mobile':phoneController.text,
      'password':passwordController.text,
      'phone_code':codeController.text
    };
    var result = await RequestManager().post(API.resetPassword,params: params);
    if (result != null && result['code'] == 200) {
      // TODO: - 登录后的逻辑
    }
  }
}